<template>
  <div class="app">
    <div class="box">
      <LeftEr
        :list="data"
        :curIndex.sync="curIndex"
        :power="power"
        :audio="$refs.audio"
      ></LeftEr>
      <RightEr
        :bank.sync="bank"
        :power.sync="power"
        :curData="curIndex + 1 ? data[curIndex] : ''"
        :volume.sync="volume"
      ></RightEr>
      <audio
        :src="src"
        @canplay="$event.target.play()"
        @ended="src = ''"
        ref="audio"
      ></audio>
    </div>
  </div>
</template>

<script>
import LeftEr from './components/LeftEr.vue' // 左边组件
import RightEr from './components/RightEr.vue' // 右边组件

export default {
  data () {
    return {
      data: null,
      curIndex: -1,
      bank: false,
      power: true,
      volume: 0,
      src: ''
    }
  },
  components: {
    LeftEr,
    RightEr
  },
  methods: {
    keydown (e) {
      const index = this.data.findIndex(v => v.keyCode === e.keyCode)
      if (index === -1) return
      this.curIndex = index
    },
    keyup () {
      this.curIndex = -1
    }
  },
  async created () {
    // 创建完成之后, 调用fetch调接口
    try {
      const res = await fetch('/bw/api/music').then(res => res.json())
      // console.log(res)
      this.data = res.data
    } catch (e) {
      console.log(e)
    }
  },
  mounted () {
    this.$refs.audio.volume = this.volume
    document.addEventListener('keydown', this.keydown)
    document.addEventListener('keyup', this.keyup)
  },
  beforeDestroy () {
    document.removeEventListener('keydown', this.keydown)
    document.removeEventListener('keyup', this.keyup)
  },
  watch: {
    volume (newVal) {
      this.$refs.audio.volume = newVal
    },
    curIndex (newVal) {
      if (newVal !== -1) this.src = this.data[newVal][this.bank ? 'bankUrl' : 'url']
    }
  }
}
</script>

<style lang="scss" scoped>
.app {
  display: flex;
  width: 100vw;
  height: 100vh;
  background: #242424;

  .box {
    margin: auto;
    border: 5px solid tomato;
    width: 900px;
    height: 500px;
    border-radius: 12px;
    background: #f0f0f0;
    box-shadow: 0 0 25px rgba($color: #eee, $alpha: 0.3);
    display: flex;
    align-items: center;
  }
}
</style>
